/*

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// import 'package:fluttertoast/fluttertoast.dart';
// import 'package:livan/main.dart';
// import 'package:livan/values/colors.dart';
// import 'package:livan/values/font.dart';
// import 'package:livan/widget/RLToast.dart';
// import 'package:livan/widget/SR_Activity_Indicator.dart';

class SingleToast{

  static final SingleToast _instance = SingleToast._internal();

  factory SingleToast(){
    return _instance._init();
  }

  bool _isLoading = false;
  int _processCount = 0;


  SingleToast _init(){
    if(_instance._context == null){
      _instance._context = navigatorKey.currentState?.overlay?.context;
    }
    return _instance;
  }

  SingleToast._internal();

  BuildContext? _context;

  String _loadingMsg = "加载中...";

  Timer? _timer = null;

  BuildContext? get context => _context;

  bool _isUpdateUI = false;  //是否正在更新UI，正在加载和移除都为true

  */
/**
   * 居中提示框
   * msg：提示信息
   *//*

  void centerToast({required String msg,bool customer = true}){
    if(customer){
      RLToast.getInstance().showFixedToast(msg);
    }else{
      Fluttertoast.showToast(msg: msg, gravity: ToastGravity.CENTER);
    }
    return;
  }

  */
/**
   * 展示loading框
   * msg：提示文字，可选
   *//*

  void loading({String msg = "加载中..."}){
    _processCount ++;
    print("-----loading current processCount:${_processCount},${_isLoading},${_isUpdateUI}------");
    _loadingMsg = msg;
    if(_context == null) {
      print("context不存在，无法加载loading...");
      return;
    }
    if(_isLoading == false && _isUpdateUI == false && _processCount > 0){
      print("------show loading-------");
      _showLoading();
    }
    return;
  }

  */
/**
   * 准备加载loading
   *//*

  void _showLoading(){
    _isUpdateUI = true;
    if(_timer == null){
      _timer = Timer.periodic(Duration(milliseconds: 60), (timer){
        print("等待Widget build");
        if(_processCount <= 0){
          print("在等待Widget build中引用计数为0，取消加载");
          timer.cancel();
          _timer =null;
          _isLoading = false;
          _isUpdateUI = false;
          return;
        }
        timer.cancel();
        _timer = null;
        try{
          print("加载loading");
          _loadingOnScreen();
          return;
        }catch(e){
          _isLoading = false;
          _isUpdateUI = false;
          print("暂时无法加载loading");
        }
      });
    }
  }

  */
/**
   * loading显示加载
   *//*

  void _loadingOnScreen(){
    showDialog(context: _context!,
        barrierDismissible: false, //点击遮罩不关闭对话框
        builder:(context){
          return ToastAlert(loadingMsg: _loadingMsg, onInit: (){
            print("loading已经展示在屏幕上");
            _isLoading = true;
            _isUpdateUI = false;
            if(_processCount <= 0){
              print("loading展示后引用计数为0，立即关闭loading");
              _isUpdateUI = true;
              _cleanLoading();
            }
          }, onDispose: (){
            print("loading已从屏幕中移除并销毁");
            _isLoading = false;
            _isUpdateUI = false;
            print("_processCount： $_processCount");
            if(_processCount > 0){
              _showLoading();
            }
          });
        }
    );
  }

  */
/**
   * 关闭loading
   *//*

  void closeLoading(){
    _processCount--;
    _processCount = max(0, _processCount);
    print("-----close loading processCount:${_processCount}--------");
    if(_context != null){
      if(_isLoading == true && _isUpdateUI == false && _processCount <= 0){
        _isUpdateUI = true;
        _cleanLoading();
      }
    }else{
      print("context不存在，不存在关闭loading条件");
    }
  }

  void _cleanLoading(){
    try{
      Navigator.of(_context!).pop();
    }catch(e){
      print('-------移除loading出错：${e}');
      _isUpdateUI == false;
    }
  }

  void alert({String title = "提示", required String message, required List<Widget> actions}){
    if(_context == null){
      print("未获取context");
      return;
    }else{
      showDialog(
          context: _context!,
          builder: (context){
            return AlertDialog(
              title: Text(title),
              content: Text(message),
              actions: actions,
            );
          }
      );
    }
  }

}

//普通loading
class ToastAlert extends StatefulWidget{

  ToastAlert({required this.loadingMsg,required this.onInit,required this.onDispose});

  final String loadingMsg;

  final Function onInit;

  final Function onDispose;

  @override
  _ToastAlertState createState() => _ToastAlertState();
}

class _ToastAlertState extends State<ToastAlert>{

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.transparent,
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: ConstrainedBox(
          constraints: BoxConstraints(
              maxWidth: 560.w
          ),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(16.w))
            ),
            padding: EdgeInsets.symmetric(horizontal: 60.w,vertical: 40.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SRCupertinoActivityIndicator(radius: 12,activityColor: ColorsValue.blue3,),
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Text(widget.loadingMsg,style: TextStyle(
                      decoration: TextDecoration.none,
                      fontSize: Font.font16,
                      color: ColorsValue.blue3,
                      fontWeight: FontWeight.normal
                  ),),
                )
              ],
            ),
          ),
        )
    );
  }

  @override
  void initState() {
    super.initState();
    widget.onInit();
    loadingDispose = widget.onDispose;
  }

  @override
  void dispose() {
    print("销毁loading----------Widget");
    if(loadingDispose != null){
      loadingDispose!();
      loadingDispose = null;
    }
    super.dispose();
  }

}

class CarControlToast{

  static final CarControlToast _instance = CarControlToast._internal();

  factory CarControlToast(){
    return _instance._init();
  }

  bool _isLoading = false;


  CarControlToast _init(){
    if(_instance._context == null){
      _instance._context = navigatorKey.currentState?.overlay?.context;
    }
    return _instance;
  }

  CarControlToast._internal();

  BuildContext? _context;

  bool readyLoadingForControl = false;

  Timer? _timer;

  bool _isUpdateUI = false;  //是否正在更新UI，正在加载和移除都为true


  void loading(String title,{String? msg,Function? disposeCallback, String timeoutLabel = '远程车控响应超时！'}){
    if(_isLoading || _isUpdateUI || _context == null) return;
    if(_timer != null){
      _timer!.cancel();
      _timer = null;
    }
    _timer = Timer.periodic(Duration(milliseconds: 60000), (timer) {
      _timer?.cancel();
      _timer = null;
      closeLoading();
      SingleToast().centerToast(msg: timeoutLabel);
    });
    _isUpdateUI = true;
    showDialog(context: _context!,
        barrierDismissible: false, //点击遮罩不关闭对话框
        barrierColor: Colors.transparent,
        builder:(context){
          return UnconstrainedBox(
            // constrainedAxis: Axis.vertical,
            child: CarControlLoading(title: title,msg: msg ?? "指令发送中···", onInit: (){
              print("loading已经展示在屏幕上");
              _isLoading = true;
              _isUpdateUI = false;
            }, onDispose: (){
              print("loading已从屏幕中移除并销毁");
              _isLoading = false;
              _isUpdateUI = false;
              if(disposeCallback != null){
                disposeCallback();
              }
            }),
          );
        }
    );
  }

  closeLoading() async {
    await Future.delayed(Duration(milliseconds: 100));
    if(!_isLoading || _isUpdateUI) return;
    _isUpdateUI = true;
    Navigator.of(_context!).pop();
    _timer?.cancel();
    _timer = null;
  }

}

//传递loading销毁方法
Function? loadingDispose;

Function? carControlLoadingDispose;

class CarControlLoading extends StatefulWidget{

  CarControlLoading({required this.title,required this.msg,required this.onInit,required this.onDispose});

  final String title;

  final String msg;

  final Function onInit;

  final Function onDispose;

  @override
  _CarControlLoadingState createState() => _CarControlLoadingState();
}

class _CarControlLoadingState extends State<CarControlLoading> with SingleTickerProviderStateMixin{

  // 是否运行动画
  bool _isAnimated = false;
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    widget.onInit();
    carControlLoadingDispose = widget.onDispose;
    _animationController =
        AnimationController(duration: const Duration(seconds: 1), vsync: this);
    _animationController.addStatusListener((status) {

      if (status == AnimationStatus.completed) {

        //动画从 controller.forward() 正向执行 结束时会回调此方法
        _animationController.repeat();

      } else if (status == AnimationStatus.dismissed) {

        //动画从 controller.reverse() 反向执行 结束时会回调此方法


      } else if (status == AnimationStatus.forward) {


        //执行 controller.forward() 会回调此状态

      } else if (status == AnimationStatus.reverse) {

        //执行 controller.reverse() 会回调此状态


      }

    });
    _animationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    if (!_isAnimated) {
      _isAnimated = true;
      _animationController.forward();
    }
    return Container(
      padding: EdgeInsets.all(25),
      decoration: BoxDecoration(
          color: Color.fromRGBO(0, 0, 0, 0.7),
          borderRadius: BorderRadius.all(Radius.circular(8))
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(widget.title,style: TextStyle(
              fontSize: Font.font14,
              fontWeight: FontWeight.bold,
              color: Colors.white,
              decoration: TextDecoration.none
          ),),
          Container(
            margin: EdgeInsets.only(top: 8),
            width: 65,
            height: 65,
            child: RotationTransition(turns: _animationController,child: Image(image: AssetImage("images/car_control_loading_customer.png"),)),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Text(widget.msg,style: TextStyle(
                fontSize: Font.font14,
                fontWeight: FontWeight.normal,
                color: Colors.white,
                decoration: TextDecoration.none
            ),),
          ),
        ],
      ),
    );
  }


  @override
  void dispose() {
    print("销毁loading----------Widget");
    _animationController.dispose();
    if(carControlLoadingDispose != null){
      carControlLoadingDispose!();
      carControlLoadingDispose = null;
    }
    super.dispose();
  }


}*/
